﻿#include "SiteDataSortToolMainWindow.h"
#include "GlobalHeader.h"

bool g_bExit = false;
DirReadThread *g_pDirReadThread = nullptr;
CSVFileReadThread *g_pCSVFileReadThread = nullptr;
LineDataDealThread *g_pLineDataDealThread = nullptr;
SiteDataSortToolMainWindow *g_pSiteDataSortToolMainWindow = nullptr;
QString g_strDealPath;

SiteDataSortToolMainWindow::SiteDataSortToolMainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    ui.setupUi(this);
	g_pSiteDataSortToolMainWindow = this;
	m_bUpdateFlag = false;
	m_LogUpdateTimer.start(200);
	ui.action_Dir->setIcon(QIcon(":/SiteDataSortTool/folderOpen.png"));
	connect(ui.action_Dir, &QAction::triggered, this, [=](bool)
	{
		const QString strFileDir = QFileDialog::getExistingDirectory(this, u8"请选择需要处理的文件夹","./Data").toUtf8();
		QDir Dir(strFileDir);
		if (strFileDir.isEmpty() || !Dir.exists())
			return;
		StopAllThread();
		g_strDealPath = strFileDir;
		if (!g_pDirReadThread)
		{
			g_pDirReadThread = new DirReadThread(nullptr);
		}		
		g_pDirReadThread->PutDirToDeal(strFileDir);
		g_pDirReadThread->start();
		
	});

	connect(&m_LogUpdateTimer, &QTimer::timeout, this, [=]
	{
		if (!m_bUpdateFlag)
			return;
		ui.listWidget_Log->addItems(m_strListLog);
		m_bUpdateFlag = false;
		m_strListLog.clear();
		ui.listWidget_Log->scrollToBottom();
	});
	AddLog(LOGTYPE_MESSAGE, u8"系统加载");
}

SiteDataSortToolMainWindow::~SiteDataSortToolMainWindow()
{
	g_bExit = true;
	g_pSiteDataSortToolMainWindow = nullptr;
	StopAllThread();
}

void SiteDataSortToolMainWindow::AddLog(LOGTYPE TYPE, const QString &strLog)
{
	//写文件
	QString strTimeAndLog = QDateTime::currentDateTime().toString("yyyyMMddHHmmsszzz");
	switch (TYPE)
	{
		case LOGTYPE_ERROR:
		{
			strTimeAndLog += "    错误    ";
		}
		break;
		case LOGTYPE_WARNING:
		{
			strTimeAndLog += "    警告    ";
		}
		break;
		case LOGTYPE_MESSAGE:
		{
			strTimeAndLog += "    信息    ";
		}
		break;
		case LOGTYPE_DEBUG:
		{
			strTimeAndLog += "    调试    ";
		}
		break;
		default:
		{
			strTimeAndLog += "    未知    ";
		}
		break;
	}
	strTimeAndLog += "  ";
	strTimeAndLog += strLog;
	m_strListLog.push_back(strTimeAndLog);
	//更新窗口
	m_bUpdateFlag = true;
}

void SiteDataSortToolMainWindow::StopAllThread()
{
	if (g_pDirReadThread)
	{
		g_pDirReadThread->requestInterruption();
		g_pDirReadThread->wait();
		delete g_pDirReadThread;
		g_pDirReadThread = nullptr;
	}
	if (g_pCSVFileReadThread)
	{
		g_pCSVFileReadThread->requestInterruption();
		g_pCSVFileReadThread->wait();
		delete g_pCSVFileReadThread;
		g_pCSVFileReadThread = nullptr;
	}
	if (g_pLineDataDealThread)
	{
		g_pLineDataDealThread->requestInterruption();
		g_pLineDataDealThread->wait();
		delete g_pLineDataDealThread;
		g_pLineDataDealThread = nullptr;
	}
}
